package algorithm.leetcode.simple;

/*
 给定一个二叉树和一个目标和，找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
 */

import java.util.ArrayList;
import java.util.List;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/10/13
 */
public class Question113 {

    public static void main(String[] args) {

    }

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<>(10);
        dfs(root, sum, new ArrayList<>(10), result);
        return result;
    }

    private void dfs(TreeNode root, int sum, ArrayList<Integer> pathList, List<List<Integer>> result) {
        if (root == null) {
            return;
        }
        ArrayList<Integer> list = new ArrayList<>(pathList);
        list.add(root.val);
        if (root.left == null && root.right == null && root.val == sum) {
            result.add(list);
            return;
        }
        dfs(root.left, sum - root.val, list, result);
        dfs(root.right, sum - root.val, list, result);
    }


    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
